<template>
    <div class="detail-task-page">
        <div>
            <van-nav-bar title="盘点任务详情" @click-left="onClickLeft" left-arrow />
        </div>
        <div>
            <tab :listData="listData" keytype="pdzc" @tab-change="onTabChange"></tab>
        </div>
        <div class="search-section">
            <vSearch placeholder="请输入资产名称" @search="onSearch"  @openpopup="openpopup" @input="onSearchInput"></vSearch>
            <vPopup ref="popupRef"></vPopup>
        </div>
        <div class="content-section">
            <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :immediate-check="false">
                <asset-card
                    v-for="(asset, index) in filteredAssets"
                    :key="`${asset.id || asset.propertyId || 'asset'}-${index}`"
                    :asset="asset"
                    :currentTab="currentTab"
                    :show-delete="shouldShowDelete(asset)"
                    :show-edit="shouldShowEdit(asset)"
                    :show-loss="shouldShowLoss(asset)"
                    :show-again-inventory="shouldShowAgain(asset)"
                    :show-inventory="shouldShowInventory(asset)"
                    :show-review="shouldShowReview(asset)"
                    :showDetail="shouldShowDetail(asset)"
                    @loss="goAssectLoss"
                    @inventory="goAssectInventory"
                    @edit="goEditAsset"
                    @delete="deleteAsset"
                    @review="reviewAsset"
                    @detail="goAssectDetail"
                />
            </van-list>
        </div>
        <div>
            <van-button v-if="currentTab == 'pdzc'" color="#3772ff" class="abtn" @click="goAssectProfit"> 盘盈 </van-button>
        </div>
    </div>
</template>
<script>
import tab from './components/tab.vue'
import vSearch from './components/vsearch.vue'
import assetCard from './components/assetCard.vue'
import vPopup from './components/vPopup.vue'
import { encrypt, decrypt } from '@/utils/crypto'
import backMixin from '../../mixins/backMixin'

export default {
    mixins: [backMixin],
    components: {
        tab,
        vSearch,
        assetCard,
        vPopup
    },
    data() {
        return {
            currentTab: 'pdzc',
            searchKeyword: '',
            loading: false,
            finished: false,
            pageNum: 1,
            pageSize: 10,
            taskId: null,
            listData: [
                { name: '盘点资产', key: 'pdzc' },
                { name: '任务事件', key: 'rwsj' }
            ],
            assets: [],
            allAssets: [],
            isLoadingData: false, // 防止重复请求的标志
            isInitialized: false, // 防止初始化时重复调用
            lastRouteId: null // 记录上次的路由 id
        }
    },
    computed: {
        filteredAssets() {
            let result = this.assets

            // 根据搜索关键词筛选
            if (this.searchKeyword && this.currentTab=='pdzc') {
                //console.log(result,'asdasd')
                result = result.filter((asset) =>
                asset.orgName.includes(this.searchKeyword))
                
            }
           
            // if (this.searchKeyword && this.currentTab=='rwsj') {
            //     console.log(result,'asdasd')
            //     result = result.filter((asset) =>
            //     asset.createbyName.includes(this.searchKeyword))
              
            // }
  return result
           
        }
    },
    watch: {
        // 监听路由参数 id 的变化
        '$route.params.id': {
            handler(newId, oldId) {
                console.log('路由 id watch 触发', { newId, oldId, isInitialized: this.isInitialized, lastRouteId: this.lastRouteId })
                // 如果已经初始化，并且 id 发生了变化，则重新加载
                if (this.isInitialized && newId) {
                    // 检查 id 是否真的发生了变化
                    if (this.lastRouteId !== null && this.lastRouteId !== newId) {
                        console.log('路由 id 变化，重新加载数据', { newId, oldId: this.lastRouteId })
                        this.lastRouteId = newId
                        this.resetAndReload()
                    } else if (this.lastRouteId === null) {
                        // 首次设置 lastRouteId
                        this.lastRouteId = newId
                    }
                }
            },
            immediate: false
        }
    },
    mounted() {
        console.log('mounted 钩子执行', { routeId: this.$route.params.id })
        // 使用 nextTick 确保在 DOM 更新后执行
        this.$nextTick(() => {
            if (!this.isInitialized) {
                console.log('首次初始化，加载数据')
                this.isInitialized = true
                this.lastRouteId = this.$route.params.id // 记录初始 id
                this.allAssets = [...this.assets]
                this.loadMoreData()
            }
        })
    },
    activated() {
        // 当从其他页面返回，并携带 query.refresh 时触发重载
        try {
            const q = this.$route && this.$route.query
            if (q && q.refresh) {
                console.log('activated 检测到 refresh，触发重载', q.refresh)
                this.$nextTick(() => {
                    this.resetAndReload()
                    // 清除 refresh 参数，避免重复触发
                    const newQuery = Object.assign({}, this.$route.query)
                    delete newQuery.refresh
                    this.$router.replace({ name: 'detailTask', params: { id: this.$route.params.id }, query: newQuery })
                })
            }
        } catch (e) {
            console.error('activated 处理 refresh 失败', e)
        }
    },
    methods: {
        // 重置状态并重新加载数据
        resetAndReload() {
            console.log('resetAndReload: 重置并重新加载数据')
            this.pageNum = 1
            this.assets = []
            this.allAssets = []
            this.finished = false
            this.loading = false
            this.searchKeyword = ''
            this.currentTab = 'pdzc'
            this.isLoadingData = false // 重置加载标志
            // 更新 lastRouteId
            this.lastRouteId = this.$route.params.id
            // 重新加载数据
            this.$nextTick(() => {
                this.loadMoreData()
            })
        },
        onClickLeft() {
            this.navigateBack()
        },
          onSearch(value){
             let result = this.assets
             if (this.searchKeyword && this.currentTab=='rwsj') {
            this.searchKeyword = value
            this.pageNum = 1
            this.tasks = []
            this.loadMoreData()
             }
            // // 根据搜索关键词筛选
            // if (this.searchKeyword && this.currentTab=='pdzc') {
            //     //console.log(result,'asdasd')
            //     result = result.filter((asset) =>
            //     asset.orgName.includes(this.searchKeyword))
            //     this.filteredAssets = result
            // }
       
           
        },
        onTabChange(tabKey) {
            console.log('onTabChange: 切换标签', { tabKey, currentTab: this.currentTab })
            // 如果切换的是同一个标签，不重新加载
            if (this.currentTab === tabKey) {
                console.log('onTabChange: 切换到相同标签，跳过')
                return
            }
            this.currentTab = tabKey
            this.assets = []
            this.pageNum = 1
            this.finished = false
            this.isLoadingData = false // 重置加载标志
            this.loadMoreData(this.currentTab)
        },
        onSearchInput(value) {
            this.searchKeyword = value
        },
        openpopup(v) {
            if (v) {
                this.$nextTick(() => {
                    this.$refs.popupRef.open()
                })
            }
        },
        onLoad() {
            if (this.finished) return

            // this.loading = true
            // setTimeout(() => {
            //     this.loadMoreData()
            //     this.loading = false
            // }, 500)
        },
        async loadMoreData(v) {
            const id = this.$route.params.id
            this.taskId = id
            if (!id) {
                console.log('loadMoreData: id 不存在，跳过请求')
                return
            }
            // 防止重复请求
            if (this.isLoadingData) {
                console.log('loadMoreData: 正在加载中，跳过重复请求')
                return
            }
            console.log('loadMoreData: 开始加载数据', { id, currentTab: this.currentTab, pageNum: this.pageNum, param: v })
            this.isLoadingData = true
            // 调用API获取数据
            try {
                const d = {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    query: {
                        keywords: this.searchKeyword,
                        businessIds: [id],
                        categories: []
                    }
                }
                const data = { id }
                if (this.currentTab == 'pdzc' || v == 'pdzc') {
                    const res = await this.$Geting(this.$api.gettaskDetailById, data)
                    if (res.code === '0' && res.data) {
                        sessionStorage.setItem('orgId', res.data.orgId)
                        const newAssets = res.data.propertyDetailWebDtoList || []
                        if (newAssets.length > 0) {
                            this.assets = [...this.assets, ...newAssets]
                            this.finished = true
                            // this.pageNum++

                        } else {
                            this.finished = true
                            this.$toast(res.message)
                        }
                    }
                } else {
                    this.finished = false
                    const res = await this.$Posting(this.$api.geteventListpage, d)
                    if (res.code === '0' && res.data) {
                        const newAssets = res.data.list || []
                        if (newAssets.length > 0) {
                            this.assets = [...this.assets, ...newAssets]
                            // this.finished = true
                            this.pageNum++
                        
                        } else {
                            this.finished = true
                            this.$toast(res.message)
                        }
                    }
                }
                
            } catch (error) {
                console.error('加载数据失败:', error)
                this.finished = true
            } finally {
                // 重置加载标志
                this.isLoadingData = false
            }
        },
        resetList() {
            this.pageNum = 1
            this.assets = [...this.allAssets]
            this.finished = false
        },
   
        /**
         * 按钮显示逻辑 - 根据后端返回的状态判断
         */
        shouldShowDelete(asset) {
            // 显示删除按钮
            const okStocktaking = asset && (asset.stocktakingResult === 1 || asset.stocktakingResult === 2)
             return okStocktaking
        },
        
        shouldShowEdit(asset) {
            // 编辑按钮：当盘点状态不等于 0 时显示（包括 undefined/null 视为不等于 0）
            const okStocktaking = asset && (asset.stocktakingResult !== 0 && asset.stocktakingResult !== null)
            return okStocktaking
        },
        shouldShowLoss(asset) {
            // 盘亏按钮：仅当盘点状态严格为 0 时显示
             const okStocktaking = asset && (asset.stocktakingResult === 0 || asset.stocktakingResult === null)
            return okStocktaking
        },
        shouldShowInventory(asset) {
            // 盘点按钮：仅当盘点状态严格为 0 时显示
              const okStocktaking = asset && (asset.stocktakingResult === 0 || asset.stocktakingResult === null)
            return okStocktaking
        },
        shouldShowAgain(asset) { 
            // 重新盘点按钮：当盘点状态为 1 或 2，并且复核结果为 0 或 null 时显示
            const okStocktaking = asset && (asset.stocktakingResult === 3)
            const okReview = asset && (asset.reviewResult === 0 || asset.reviewResult === null)
            return okStocktaking && okReview
        },
        shouldShowDetail(asset) {
            // 详情按钮：当盘点状态不等于 0 且不为 null 时显示
            return asset && asset.stocktakingResult !== 0 && asset.stocktakingResult !== null
        },
        shouldShowReview(asset) {
            // 复核按钮：当盘点状态不等于 0 且不为 null，并且复核结果为 0 或 null 时显示
            const okStocktaking = asset && asset.stocktakingResult !== 0 && asset.stocktakingResult !== null
            const okReview = asset && (asset.reviewResult === 0 || asset.reviewResult === null)
            return okStocktaking && okReview
        },
        goAssectDetail(asset) {   //详情
            const secretKey = '2D2859D8004F2FDC7300002A26A6C465'    
            const encryptedK = encrypt(asset.propertyId, secretKey)
         
            this.$router.push({ name: 'pmd', query: { k: encryptedK } })
        },
        goAssectLoss(asset) {
            console.log(asset,'asset')
            let data = JSON.stringify({
    attachmentWebDtoList: [],
    taskId: asset.taskId,
    stocktakingResult: asset.stocktakingResult,
    action: 2,
    remark: "",
    taskPropertyId:asset.propertyId,
    id:asset.id
})
            this.$router.push({ name: 'assectLoss', params: { data: encodeURIComponent(data) } })
        },
        goAssectProfit() {
            let data = JSON.stringify({
                attachmentWebDtoList: [],
                // taskId: asset.taskId,
                // stocktakingResult: asset.stocktakingResult,
                // action: 1,
                // remark: "",
                // taskPropertyId:asset.propertyId,
               // id:asset.id
            })
            this.$router.push({ name: 'assectProfit', query: { taskId: this.taskId }})
        },
        goAssectInventory(asset) {
        //    console.log(asset.propertyId,'asset.propertyId')
            const secretKey = '2D2859D8004F2FDC7300002A26A6C465'    
            const encryptedK = encrypt(asset.propertyId, secretKey)
         
            this.$router.push({ name: 'pdEdit', query: { k: asset.typeId ,id:asset.propertyId,taskPropertyId:asset.id} })
        },
        goEditAsset(asset) {
            // 编辑资产
            console.log('编辑资产:', asset)
             this.$store.commit('assectData/setAssectInfo', asset)
             this.$router.push({ name: 'assectProfit', query: { taskId: this.taskId }})
        },
        deleteAsset(asset) {
            // 删除资产
            this.$dialog
                .confirm({
                    title: '确认删除',
                    message: '确定要删除该资产吗？'
                })
                .then(() => {
                    let data = {
                        id:asset.id
                    }
                let res =  this.$Geting(this.$api.getTaskDel, this.data) 
                console.log(res)
                if (res.code === '0' && res.data) {
                    console.log(res, 'res')
                   
                    this.$toast('删除成功')
                }else{
                    this.$toast(res.message)
                }
                 
                })
                .catch(() => {})
        },
        reviewAsset(asset) {
            // 复核通过
            this.$dialog
                .confirm({
                    title: '确认复核',
                    message: '确定要复核通过该资产吗？'
                })
                .then(() => {
                    let data = {
                        taskPropertyId:asset.propertyId
                    }
                let res =  this.$Geting(this.$api.getreStocktaking, this.data) 
                console.log(res)
                if (res.code === '0' && res.data) {
                    console.log(res, 'res')
                    this.$toast('复核通过')
                }else{
                    this.$toast(res.message)
                }
                 
                })
                .catch((error) => {
                    this.$toast(error)
                })
        }
    }
}
</script>
<style scoped>
.detail-task-page {
    background-color: #f5f5f5;
    min-height: 100vh;
}

.search-section {
    padding: 10px 15px;
    background-color: #fff;
}

.content-section {
    padding: 10px 15px;
    padding-bottom: 20px;
    height: 75vh;
    overflow-y: auto;
}
.abtn {
    position: absolute;
    bottom: 100px;
    width: 40vw;
    left: 30vw;
}
</style>
